The async
and await
keywords in JavaScript provide a way to work with asynchronous code
in a more readable and manageable manner. They are built on top of Promises and make asynchronous code look more
like synchronous code.
An async
function is a function that returns a Promise. The async
keyword is placed
before a function declaration to define an asynchronous function:
async function myFunction() {
return "Hello, World!";
}
myFunction().then(value => console.log(value)); // Outputs: Hello, World!
The await
keyword can only be used inside an async
function. It makes JavaScript wait
until the Promise settles and returns its result:
async function fetchData() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 2000);
});
let result = await promise; // Wait until the promise resolves
console.log(result); // Outputs: Data fetched
}
fetchData();
You can handle errors in async
functions using try...catch
blocks:
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Here is an example demonstrating how to access and manipulate child elements:
// HTML
// <div id="parent">
// <div class="child">Child 1</div>
// <div class="child">Child 2</div>
// </div>
let parent = document.getElementById('parent');
let children = parent.getElementsByClassName('child');
for (let i = 0; i < children.length; i++) {
children[i].style.color = 'blue';
}
For more detailed information, you can check out resources like W3Schools[^1^][2] and MDN Web Docs[^2^][1].